<template>
  <div class="order-list">
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
      <h2>订单管理</h2>
          <p>管理您的所有订单和交易记录</p>
        </div>
        <div class="header-actions">
          <a-button @click="exportOrders">
            <DownloadOutlined />
            导出订单
          </a-button>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-row">
      <a-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon pending-icon">
            <ClockCircleOutlined />
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ orderStats.pending }}</div>
            <div class="stat-label">待处理</div>
          </div>
        </div>
      </a-card>

      <a-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon paid-icon">
            <CheckCircleOutlined />
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ orderStats.paid }}</div>
            <div class="stat-label">已支付</div>
          </div>
        </div>
      </a-card>

      <a-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon completed-icon">
            <TrophyOutlined />
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ orderStats.completed }}</div>
            <div class="stat-label">已完成</div>
          </div>
        </div>
      </a-card>

      <a-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon refunded-icon">
            <RollbackOutlined />
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ orderStats.refunded }}</div>
            <div class="stat-label">已退款</div>
          </div>
        </div>
      </a-card>
    </div>

    <!-- 搜索和筛选 -->
    <a-card class="search-card" :bordered="false">
      <a-form layout="inline" :model="searchForm" @finish="handleSearch">
        <a-row :gutter="16" style="width: 100%">
          <a-col :span="6" :xs="24" :sm="12" :md="6">
            <a-form-item>
          <a-input
            v-model:value="searchForm.keyword"
            placeholder="搜索订单号或课程名称"
            allow-clear
                :prefix="SearchOutlined"
          />
            </a-form-item>
        </a-col>
          <a-col :span="4" :xs="24" :sm="12" :md="4">
            <a-form-item>
          <a-select
            v-model:value="searchForm.status"
            placeholder="订单状态"
            allow-clear
                style="width: 100%"
          >
                <a-select-option value="pending">待处理</a-select-option>
            <a-select-option value="paid">已支付</a-select-option>
            <a-select-option value="completed">已完成</a-select-option>
            <a-select-option value="refunded">已退款</a-select-option>
          </a-select>
            </a-form-item>
        </a-col>
          <a-col :span="6" :xs="24" :sm="12" :md="6">
            <a-form-item>
              <a-range-picker
            v-model:value="searchForm.dateRange"
                placeholder="['开始日期', '结束日期']"
            style="width: 100%"
          />
            </a-form-item>
        </a-col>
          <a-col :span="6" :xs="24" :sm="12" :md="6">
            <a-form-item>
              <a-space>
                <a-button type="primary" html-type="submit" :loading="searching">
            <SearchOutlined />
            搜索
          </a-button>
                <a-button @click="resetSearch">
                  <ReloadOutlined />
                  重置
                </a-button>
              </a-space>
            </a-form-item>
        </a-col>
      </a-row>
      </a-form>
    </a-card>

    <!-- 订单列表 -->
    <a-card class="list-card" :bordered="false" :loading="loading">
      <template #extra>
        <a-space>
          <a-button @click="refreshData" :loading="refreshing">
            <ReloadOutlined />
            刷新
          </a-button>
          <a-dropdown>
            <a-button>
              批量操作 <DownOutlined />
            </a-button>
            <template #overlay>
              <a-menu @click="handleBatchAction">
                <a-menu-item key="complete">批量完成</a-menu-item>
                <a-menu-item key="export">批量导出</a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </a-space>
      </template>

      <a-table
        :columns="columns"
        :data-source="orderList"
        :loading="loading"
        :pagination="pagination"
        :row-selection="rowSelection"
        @change="handleTableChange"
        :scroll="{ x: 1200 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'orderNo'">
            <a @click="viewOrderDetail(record)" class="order-link">
              {{ record.orderNo }}
            </a>
          </template>
          
          <template v-else-if="column.key === 'courseInfo'">
            <div class="course-info">
              <a-image
                :src="record.courseCover"
                :width="60"
                :height="45"
                :fallback="defaultCover"
                class="course-cover"
              />
              <div class="course-details">
                <div class="course-title">{{ record.courseTitle }}</div>
                <div class="course-category">{{ record.courseCategory }}</div>
              </div>
            </div>
          </template>
          
          <template v-else-if="column.key === 'studentInfo'">
            <div class="student-info">
              <a-avatar :src="record.studentAvatar" :size="32">
                <UserOutlined />
              </a-avatar>
              <div class="student-details">
                <div class="student-name">{{ record.studentName }}</div>
                <div class="student-email">{{ record.studentEmail }}</div>
              </div>
            </div>
          </template>
          
          <template v-else-if="column.key === 'amount'">
            <span class="amount">¥{{ record.amount }}</span>
          </template>
          
          <template v-else-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>
          
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="viewOrderDetail(record)">
                <EyeOutlined />
                查看
              </a-button>
              <a-dropdown>
                <a-button type="link" size="small">
                  操作 <DownOutlined />
                </a-button>
                <template #overlay>
                  <a-menu @click="handleMenuClick">
                    <a-menu-item key="complete" v-if="record.status === 'paid'">
                      <CheckCircleOutlined />
                      标记完成
                    </a-menu-item>
                    <a-menu-item key="refund" v-if="record.status === 'paid'">
                      <RollbackOutlined />
                      退款
                    </a-menu-item>
                    <a-menu-item key="export">
                      <DownloadOutlined />
                      导出
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import {
  DownloadOutlined,
  SearchOutlined,
  ReloadOutlined,
  DownOutlined,
  EyeOutlined,
  CheckCircleOutlined,
  RollbackOutlined,
  ClockCircleOutlined,
  TrophyOutlined,
  UserOutlined
} from '@ant-design/icons-vue'

const router = useRouter()

// 状态管理
const loading = ref(false)
const searching = ref(false)
const refreshing = ref(false)

// 搜索表单
const searchForm = ref({
  keyword: '',
  status: '',
  dateRange: []
})

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) => 
    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
})

// 选中的行
const selectedRowKeys = ref<string[]>([])
const rowSelection = computed(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: string[]) => {
    selectedRowKeys.value = keys
  }
}))

// 订单统计数据
const orderStats = ref({
  pending: 12,
  paid: 89,
  completed: 156,
  refunded: 8
})

// 订单列表数据
const orderList = ref([
  {
    key: '1',
    id: 1,
    orderNo: 'ORD2024001',
    courseTitle: 'AI基础入门课程',
    courseCover: 'https://via.placeholder.com/60x45/667eea/ffffff?text=AI',
    courseCategory: 'AI技术',
    studentName: '张三',
    studentEmail: 'zhangsan@example.com',
    studentAvatar: '',
    amount: 299,
    status: 'paid',
    createTime: '2024-01-15 10:30:00',
    payTime: '2024-01-15 10:35:00'
  },
  {
    key: '2',
    id: 2,
    orderNo: 'ORD2024002',
    courseTitle: '机器学习实战',
    courseCover: 'https://via.placeholder.com/60x45/f093fb/ffffff?text=ML',
    courseCategory: 'AI技术',
    studentName: '李四',
    studentEmail: 'lisi@example.com',
    studentAvatar: '',
    amount: 599,
    status: 'completed',
    createTime: '2024-01-14 15:20:00',
    payTime: '2024-01-14 15:25:00'
  },
  {
    key: '3',
    id: 3,
    orderNo: 'ORD2024003',
    courseTitle: '前端开发进阶',
    courseCover: 'https://via.placeholder.com/60x45/4facfe/ffffff?text=FE',
    courseCategory: '编程开发',
    studentName: '王五',
    studentEmail: 'wangwu@example.com',
    studentAvatar: '',
    amount: 399,
    status: 'pending',
    createTime: '2024-01-13 09:15:00',
    payTime: null
  }
])

// 表格列定义
const columns = [
  {
    title: '订单号',
    dataIndex: 'orderNo',
    key: 'orderNo',
    width: 120,
    fixed: 'left'
  },
  {
    title: '课程信息',
    dataIndex: 'courseInfo',
    key: 'courseInfo',
    width: 200
  },
  {
    title: '学员信息',
    dataIndex: 'studentInfo',
    key: 'studentInfo',
    width: 180
  },
  {
    title: '金额',
    dataIndex: 'amount',
    key: 'amount',
    width: 100
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 150
  },
  {
    title: '支付时间',
    dataIndex: 'payTime',
    key: 'payTime',
    width: 150
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right'
  }
]

// 默认封面
const defaultCover = 'https://via.placeholder.com/60x45/cccccc/ffffff?text=No+Image'

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    pending: 'orange',
    paid: 'blue',
    completed: 'green',
    refunded: 'red'
  }
  return colorMap[status] || 'default'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    pending: '待处理',
    paid: '已支付',
    completed: '已完成',
    refunded: '已退款'
  }
  return textMap[status] || '未知'
}

// 搜索处理
const handleSearch = async () => {
  searching.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 500))
    console.log('搜索条件:', searchForm.value)
    message.success('搜索完成')
  } catch (error) {
    message.error('搜索失败')
  } finally {
    searching.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    keyword: '',
    status: '',
    dateRange: []
  }
  handleSearch()
}

// 刷新数据
const refreshData = async () => {
  refreshing.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 1000))
    message.success('数据已刷新')
  } catch (error) {
    message.error('刷新失败')
  } finally {
    refreshing.value = false
  }
}

// 表格变化处理
const handleTableChange = (pag: any, filters: any, sorter: any) => {
  pagination.value.current = pag.current
  pagination.value.pageSize = pag.pageSize
  console.log('表格变化:', { pag, filters, sorter })
}

// 批量操作
const handleBatchAction = ({ key }: { key: string }) => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请选择要操作的订单')
    return
  }

  switch (key) {
    case 'complete':
      Modal.confirm({
        title: '确认完成',
        content: `确定要标记选中的 ${selectedRowKeys.value.length} 个订单为已完成吗？`,
        onOk: () => {
          message.success('批量操作成功')
          selectedRowKeys.value = []
        }
      })
      break
    case 'export':
      message.success('批量导出功能开发中...')
      break
  }
}

// 菜单点击处理
const handleMenuClick = ({ key, keyPath }: { key: string, keyPath: string[] }) => {
  console.log('菜单点击:', key, keyPath)
  // 这里可以实现具体的操作逻辑
}

// 查看订单详情
const viewOrderDetail = (record: any) => {
  console.log('查看订单详情:', record)
  // 这里可以实现查看订单详情的逻辑
}

// 导出订单
const exportOrders = () => {
  message.success('导出功能开发中...')
}

// 组件挂载时初始化
onMounted(() => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    pagination.value.total = orderList.value.length
  }, 1000)
})
</script>

<style scoped>
.order-list {
  padding: 0;
}

.page-header {
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 24px;
}

.header-left h2 {
  font-size: 24px;
  color: #333;
  margin-bottom: 8px;
  font-weight: 600;
}

.header-left p {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.header-actions {
  flex-shrink: 0;
}

.stats-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.pending-icon {
  background: linear-gradient(135deg, #faad14 0%, #ffc53d 100%);
}

.paid-icon {
  background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
}

.completed-icon {
  background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
}

.refunded-icon {
  background: linear-gradient(135deg, #ff4d4f 0%, #ff7875 100%);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  line-height: 1;
}

.stat-label {
  color: #666;
  font-size: 12px;
  margin-top: 4px;
}

.search-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.list-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.order-link {
  color: #1890ff;
  text-decoration: none;
}

.order-link:hover {
  text-decoration: underline;
}

.course-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.course-cover {
  border-radius: 4px;
  object-fit: cover;
}

.course-details {
  flex: 1;
}

.course-title {
  font-size: 14px;
  color: #333;
  font-weight: 500;
  margin-bottom: 4px;
}

.course-category {
  font-size: 12px;
  color: #666;
}

.student-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.student-details {
  flex: 1;
}

.student-name {
  font-size: 14px;
  color: #333;
  font-weight: 500;
  margin-bottom: 4px;
}

.student-email {
  font-size: 12px;
  color: #666;
}

.amount {
  color: #f5222d;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 16px;
  }
  
  .header-left h2 {
    font-size: 20px;
  }
  
  .stats-row {
    grid-template-columns: 1fr;
  }
  
  .search-card .ant-form-item {
    margin-bottom: 16px;
  }
}

@media (max-width: 480px) {
  .page-header {
    margin-bottom: 16px;
  }
  
  .stats-row {
    margin-bottom: 16px;
  }
  
  .search-card,
  .list-card {
    margin-bottom: 16px;
  }
}
</style>
